
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.ChoiceGroup;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class HostDB extends Thread {

    private CliDB cli = null;
    private MLet mlet = null;
    private HttpConnection conn = null;
    private Hashtable tab = null;
    private String req_xml = "";
    private AnswerParser parser = null;

    int id = 0;

    private boolean isCancel = false;
    private String email = "";
    private String password = "";

    public HostDB(MLet midlet)
    {
        cli = CliDB.getInstance();
        tab = new Hashtable();
        mlet = midlet;
    }

    public void run()
    {
        isCancel = false;
        send();
        System.out.println("run: after send");
    }

    public void cancel()
    {
        try
        {
            isCancel = true;
            if (conn != null)
            {
                conn.close();
                conn = null;
            }
        }
        catch (IOException e)
        {
            System.out.println(e.getClass() +": "+e.getMessage());
        }
    }

    public void login(String Email, String Password)
    {
        cli.setPassword(null);
        this.email = Email;
        this.password = Password;
        req_xml = "xml="+ wrap("user", "login");
        start();
    }

    public void searchEvent()
    {
        // ChoiceGroup grp = mlet.getChoiceGroup();
        String categ = null;
        /*
        if(grp.isSelected(0))
            categ = "sub";
        else if(grp.isSelected(1))
            categ = "own";
        else if(grp.isSelected(2))
            categ = "sha";

         *
         */
        queryEvents(null, CliDB.getInstance().getCityID(), mlet.base_date, categ);
    }

    public void searchUserEvent(String UserID)
    {
        queryEvents(UserID, null, null, null);
    }

    public void searchCityEvent(String CityID)
    {
        queryEvents(null, CityID, null, null);
    }

    public void queryEvents(String UserID, String CityID, Date BegDT, String Categ)
    {
        mlet.plan_list_title = makePlansTitle();
        tab.clear();
        if(UserID != null) tab.put("user_id", UserID);
        if(CityID != null) tab.put("city_id", CityID);
        if(BegDT != null) tab.put("date", HostDB.date2uni(BegDT));
        if(Categ != null) tab.put("categ", Categ);
        req_xml = "xml="+ wrap("plan", "get");
        start();
    }

    public void findEvents(String Find, Date BegDT, String CityID)
    {
        mlet.plan_list_title = makePlansTitle();
        tab.clear();
        if(Find != null) tab.put("find", Find);
        if(CityID != null) tab.put("city_id", CityID);
        if(BegDT != null) tab.put("date", HostDB.date2uni(BegDT));
        req_xml = "xml="+ wrap("plan", "find");
        start();
    }

    private String makePlansTitle()
    {
        String t = "";
        if(mlet.base_date != null)
        {
            System.out.println(mlet.base_date.toString());
            t += " " + HostDB.date2rus(mlet.base_date);
        }
        // город учитывается только для поиска событий без категорий
        //
        /*
        if((CliDB.getInstance().getCity() != null) && (Categ.length() == 0))
            t += " " + mlet.getStrCity().getText();
        if(UserID != null)
            t += " " + mlet.username;
         *
         */
         return t.trim();
    }

    public void queryUsers(String LinkType, String UserID)
    {
        tab.clear();
        tab.put("link", LinkType);
        if(UserID != null) tab.put("user_id", UserID);
        req_xml = "xml="+ wrap("user", "links");
        start();
    }

    public void findUsers(String Find)
    {
        tab.clear();
        tab.put("find", Find);
        req_xml = "xml="+ wrap("user", "find");
        start();
    }

    public void queryCountries()
    {
        tab.clear();
        req_xml = "xml="+ wrap("country", "get");
        start();
    }

    public void queryRegions(String CountryID)
    {
        tab.clear();
        tab.put("country_id", CountryID);
        req_xml = "xml="+ wrap("region", "get");
        start();
    }

    public void queryCities(String RegionID)
    {
        tab.clear();
        tab.put("region_id", RegionID);
        req_xml = "xml="+ wrap("city", "get");
        start();
    }

    public void send()
    {
        conn = null;
        try
        {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(bout);

            dout.write(req_xml.getBytes("UTF-8"));
            byte[] bytes = bout.toByteArray();
            dout.close();

            conn = (HttpConnection) Connector.open(Conf.URL);
            conn.setRequestMethod(HttpConnection.POST);
            conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
            conn.setRequestProperty("Content-Language", "ru-RU");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));

            System.out.println("HostDB.send connection opened "+ conn.getURL());

            OutputStream os = conn.openOutputStream();
            os.write(bytes);
            os.close();
            System.out.println("HostDB.send data sent");
            System.out.println(req_xml);

            if(isCancel == false)
            {
                KXmlParser prs = new KXmlParser();
                try
                {
                    prs.setInput(conn.openInputStream(), "UTF-8");
                    System.out.println("HostDB.send data parsing");
                    parser = new AnswerParser(mlet.items);
                    parser.execute(prs);
                    if(parser.ecode.equals("0"))
                    {
                        if(parser.obj.equals("user"))
                        {
                            if(parser.act.equals("login"))
                            {
                                System.out.println("password = "+ password);
                                // на всякий случай проверяем стартовые значения
                                if(email.length() > 0)
                                {
                                    // записываем в RMS
                                    cli.setEMail(email);
                                    cli.setPassword(password);
                                    if(mlet.items.size() == 1)
                                    {
                                        mlet.item = (UniItem) mlet.items.elementAt(0);
                                        mlet.actor_id = mlet.item.getStr("uid");
                                        cli.setCity(mlet.item.getStr("city"));
                                        cli.setCityID(mlet.item.getStr("cid"));
                                        cli.setUsername(mlet.item.getStr("username"));
                                    }
                                }
                                mlet.onLoginOK();
                            }
                            else if(parser.act.equals("find"))
                            {
                                mlet.showUsers();
                            }
                            else if(parser.act.equals("links"))
                            {
                                System.out.println("before show user links");
                                mlet.showUsers();
                            }
                        }
                        else if(parser.obj.equals("plan"))
                        {
                            mlet.showPlans();
                        }
                        else if(parser.obj.equals("country"))
                        {
                            mlet.showCountries();
                        }
                        else if(parser.obj.equals("region"))
                        {
                            mlet.showRegions();
                        }
                        else if(parser.obj.equals("city"))
                        {
                            mlet.showCities();
                        }
                    }
                    else
                    {
                        if(parser.ecode.equals("2"))
                        {
                            cli.setPassword(null);
                            mlet.onLoginError(parser.error);
                        }
                        else
                        {
                            // mlet.goBack();
                        }

                    }
                }
                catch(XmlPullParserException e)
                {
                    System.out.println(e.getClass() + ": "+ e.getMessage());
                    e.printStackTrace();
                }

                conn.close();
            }
            conn = null;
            System.out.println("HostDB.send finished");
        }
        catch(java.lang.NullPointerException e)
        {
            System.out.println(e.getClass() + ": "+ e.getMessage());
        }
        catch (IOException e) {
            System.out.println(e.getClass() + ": "+ e.getMessage());
        }
        isCancel = false;
    }

    private String wrap(String obj, String act)
    {
        String cliPassword = cli.getPassword();
        if(cliPassword == null)
            return wrap(obj, act, email, password);
        else
            return wrap(obj, act, cli.getEMail(), cliPassword);
    }

    private String wrap(String obj, String act, String email, String password)
    {
        id++;
        String xml  = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        xml += "<pack><req  id=\""+ Integer.toString(id) +"\" o=\""+ obj +"\" a=\""+ act +"\" m=\""+ email +"\" p=\""+ password +"\" >";

        Enumeration keys = tab.keys();
        while(keys.hasMoreElements())
        {
            String key = (String)keys.nextElement();
            String val = (String)tab.get(key);
            xml += "<p n=\""+ key +"\" v=\""+ val +"\" />";
        }

        xml += "</req></pack>";
        return xml;
    }

    public boolean isLogin()
    {
        return !(cli.getPassword() == null);
    }

    public static String date2uni(Date date)
    {
        Calendar c = Calendar.getInstance() ;
        c.setTime(date);
        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH) + 1;
        int d = c.get(Calendar.DATE);
        String t = y+"-"+(m<10?"0": "")+m+"-"+(d<10?"0":"")+d;
        return t;
    }

    public static String date2rus(Date date)
    {
        Calendar c = Calendar.getInstance() ;
        c.setTime(date);
        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH) + 1;
        int d = c.get(Calendar.DATE);
        String t = (d<10?"0":"")+d+"."+(m<10?"0": "")+m+"."+y;
        return t;
    }

}
